/**
 * 时间相关工具函数
 * @param {number} params - 0: 时分秒（默认）, 1: 时间戳, 2: 完整时间戳
 * @returns {string|number} 格式化的时间或时间戳
 */
function timeParams(params = 0) {
  const date = new Date();
  const time = Date.now();
  const year = date.getFullYear().toString();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const hour = date.getHours().toString().padStart(2, "0");
  const minute = date.getMinutes().toString().padStart(2, "0");
  const second = date.getSeconds().toString().padStart(2, "0");
  const milliseconds = String(date.getMilliseconds()).padStart(3, "0");
  const timestamp = `${year}-${month}-${day} ${hour}:${minute}:${second}.${milliseconds}`;

  return params === 0
    ? `${month}${day}${hour}${minute}${second}`
    : params === 1
    ? time
    : timestamp;
}

/**
 * 如果a在b的前方则返回true，否则返回false
 * @param {number} a - 第一个位置
 * @param {number} b - 第二个位置
 * @param {number} totalplates - 总鳞片数
 * @returns {boolean}
 */
function ifinfront(a, b, totalplates) {
  const d1 = caclDistance(a, b, totalplates);
  let d2 = b - a;
  if (d2 < 0) {
    d2 += totalplates;
  }
  return d1 === d2;
}

/**
 * 计算两个点的距离
 * @param {number} p1 - 第一个点
 * @param {number} p2 - 第二个点
 * @param {number} totalplates - 总鳞片数
 * @returns {number} - 最短距离
 */
function caclDistance(p1, p2, totalplates) {
  const differenceValues1 = Math.abs(p1 - p2);
  const differenceValues2 = totalplates - differenceValues1;
  return Math.min(differenceValues1, differenceValues2);
}

/**
 * 获取本地IP地址
 * @returns {string[]} IP地址列表
 */
function getLocalIP() {
  const networkInterfaces = require("os").networkInterfaces();
  const ips = [];
  
  for (const key of Object.keys(networkInterfaces)) {
    for (const nic of networkInterfaces[key]) {
      if (!nic.internal && nic.family === "IPv4") {
        ips.push(nic.address);
      }
    }
  }
  
  return ips;
}


/**
 * UDP消息发送工具
 * @param {string} topic - 消息主题
 * @param {Object} obj - 消息内容
 * @param {Object} udpClients - UDP客户端对象
 */
function sendUdp(topic, obj, udpClients) {
  try {
    const formattedMessage = JSON.stringify(obj, null, 2);
    const sendWithRetry = () => {
      try {
        if (topic === "rfids") {
          udpClients.rfid.send(formattedMessage);
        } else {
          udpClients.main.send(formattedMessage);
        }
      } catch (err) {
        console.error("UDP send error:", err);
      }
    };
    sendWithRetry();
  } catch (err) {
    console.error("Error formatting UDP message:", err);
  }
}

/**
 * 消息发送工具
 * @param {string} topic - 消息主题
 * @param {Object} message - 消息内容
 * @param {Object} options - 配置选项
 */
function sendMessage(topic, message, { savedata = false, udpClients, logPath, window } = {}) {
  const UDP_TOPICS = ["baseMap", "addWindow", "updateWindow", "removeWindow", "rfids"];
  
  if (UDP_TOPICS.includes(topic)) {
    sendUdp(topic, message, udpClients);
  }

  if (savedata) {
    saveMessageToLog(topic, message, logPath);
  }

  // 向渲染进程发送消息
  if (window && window.webContents) {
    window.webContents.send(topic, message);
  }
}

/**
 * 解析IATA RFID标签内容（RP174C标准）
 * @param {string} EPCstring - RFID标签数据
 * @returns {Object} 解析后的标签信息
 */
function getLPCfromEPC(EPCstring) {
  // 验证基本格式
  if (!EPCstring || typeof EPCstring !== 'string') {
    return {
      success: false,
      bid: '',
      jfd: '',
      error: 'Invalid 标签数据'
    };
  }

  // 去掉前两个字符
  EPCstring = EPCstring.substring(2);

  try {
    const result = {
      protocolControl1: '',
      dsfid: '',
      bidPrecursor: '',
      bidLength: '',
      bid: '',
      jfdPrecursor: '',
      jfdLength: '',
      jfd: '',
      isHexBID: false,
      isHexJFD: false
    };

    // 解析Protocol Control Byte 1 (固定为C1)
    result.protocolControl1 = EPCstring.substring(0, 2);
    if (result.protocolControl1 !== 'C1') {
      return {
        success: false,
        bid: '',
        jfd: '',
        error: `Protocol Control Byte 1 is ${result.protocolControl1}, not C1`
      };
    }

    // 解析DSFID (固定为0C)
    result.dsfid = EPCstring.substring(2, 4);
    if (result.dsfid !== '0C') {
      return {
        success: false,
        bid: '',
        jfd: '',
        error: `DSFID is ${result.dsfid}, not 0C`
      };
    }

    // 解析BID Precursor (11或21)
    result.bidPrecursor = EPCstring.substring(4, 6);
    if (!['11', '21'].includes(result.bidPrecursor)) {
      return {
        success: false,
        bid: '',
        jfd: '',
        error: `BID Precursor is ${result.bidPrecursor}, not 11 or 21`
      };
    }
    result.isHexBID = result.bidPrecursor[0] === '1';

    // 解析BID Length
    result.bidLength = EPCstring.substring(6, 8);
    const bidLen = parseInt(result.bidLength, 16);
    if (bidLen !== 4 && bidLen !== 5) {
      return {
        success: false,
        bid: '',
        jfd: '',
        error: `Invalid BID Length: ${result.bidLength}`
      };
    }

    // 解析BID (行李标签号)
    const bidStart = 8;
    const bidEnd = bidStart + (bidLen * 2); // 每个字节用两个十六进制字符表示
    result.bid = EPCstring.substring(bidStart, bidEnd);
    result.bid = result.isHexBID ? parseInt(result.bid, 16).toString() : result.bid;
    result.success = true;
    // 解析JFD Precursor (12或22)
    result.jfdPrecursor = EPCstring.substring(bidEnd, bidEnd + 2);
    if (!['12', '22'].includes(result.jfdPrecursor)) {
       result.warning = `JFD Precursor is ${result.jfdPrecursor}, not 12 or 22`;
    }
    result.isHexJFD = result.jfdPrecursor[0] === '1';

    // 解析JFD Length
    result.jfdLength = EPCstring.substring(bidEnd + 2, bidEnd + 4);
    const jfdLen = parseInt(result.jfdLength, 16);
    if (jfdLen <= 0) {
        result.warning = `Invalid JFD Length: ${result.jfdLength}`;
    }

    // 解析JFD (航班日期)
    result.jfd = EPCstring.substring(bidEnd + 4, bidEnd + 4 + (jfdLen * 2));

    // 转换BID和JFD为实际值
    result.jfd = result.isHexJFD ? parseInt(result.jfd, 16).toString() : result.jfd;

    return result;
  } catch (error) {
    return {
      success: false,
      bid: '',
      jfd: '',
      error: `${error.message}`
    };
  }
}

/**
 * 本地测试RFID标签解析
 * @param {string} tagString - 要测试的RFID标签字符串
 */
function testRFIDParse(tagString) {
  try {
    const startTime = process.hrtime();
    const result = getLPCfromEPC(tagString);
    const endTime = process.hrtime(startTime);
    const duration = (endTime[0] * 1000 + endTime[1] / 1000000).toFixed(3);
    
    console.log('Input RFID tag string:', tagString);
    console.log('-------------------Parse Result-------------------');
    console.log('Parse status:', result.success ? 'Success' : 'Failed');
    if (result.success) {
      console.table(result);
    } else {
      console.log('Error message:', result.error);
    }
    console.log('Parse duration:', duration, 'ms');
    console.log('---------------------------------------------');
    
    return result;
  } catch (error) {
    console.error('解析错误:', error.message);
    return null;
  }
}

// 如果直接运行此文件，处理命令行参数
if (require.main === module) {
  const args = process.argv.slice(2);
  for (const arg of args) {
    if (arg.startsWith('--testRFIDtag=')) {
      const tagString = arg.split('=')[1];
      testRFIDParse(tagString);
    }
  }
}
class Log {
  constructor() {
    this.text = '';
  }
  new(timestamp) {
    this.text = JSON.stringify({timestamp});
    this.lines = 1;
  }
  add(text) {
    this.text += '\n';
    this.text += text;
    this.lines++;
  }
}
module.exports = {
  Log,
  timeParams,
  ifinfront,
  caclDistance,
  getLocalIP,
  sendMessage,
  sendUdp,
  getLPCfromEPC,
  testRFIDParse
};
